package dao;

import bean.Course;
import bean.Student;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.List;

public class CourseDAOImpl implements CourseDAO {
    private Session session;
    private Transaction transaction;
    private boolean completed;

    public CourseDAOImpl(Session session) {
        this.session = session;
    }

    @Override
    public boolean add(Course course) {
        try {
            transaction = session.beginTransaction();
            Student student = session.get(Student.class, course.getStudentId());
            course.setStudent(student);
            student.setCourse(course);
            session.save(course);
            session.update(student);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
            session.close();
        }
        return completed;
    }

    @Override
    public boolean modify(Course course) {
        try {
            transaction = session.beginTransaction();
            session.update(course);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
            session.close();
        }
        return completed;
    }

    @Override
    public boolean remove(int studentId) {
        try {
            transaction = session.beginTransaction();
            Course course = session.get(Course.class, studentId);
            Student student = course.getStudent();
            student.setCourse(null);
            session.delete(course);
            session.update(student);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
            session.close();
        }
        return completed;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Course> queryAll() {
        List<Course> courses = null;
        try {
            Query<Course> query = session.createQuery("FROM Course ORDER BY studentId");
            courses = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return courses;
    }

    @Override
    public Course query(int studentId) {
        Course course;
        try {
            @SuppressWarnings("unchecked")
            Query<Course> query = session.createQuery("FROM Course WHERE studentId=" + studentId);
            course = (Course) query.list().get(0);
        } catch (Exception e) {
            course = null;
            e.printStackTrace();
        } finally {
            session.close();
        }
        return course;
    }
}
